from order_manager.model.orders import Order
# from order_manager.controller.utils import read_json, write_json


class OrderController:
    def __init__(self, user_controller):
        self.orders: list[Order] = []
        self.user_controller = user_controller

    def auth(self, func):
        """
        装饰器，登录用户为管理员是才允许进行操作
        """

        def check_admin():
            if self.user_controller.current_user == 'admin':
                func()
            else:
                print('权限不足')

        return check_admin

    def add_order(self, product_name, product_price, product_quantity):
        """
        新增订单
        :return:
        """

        order_id = self.gen_order_id()

        if order_id in self.orders:
            print('订单已存在')
            return False
        else:
            self.orders.append(
                Order(order_id=order_id, product_name=product_name, quantity=product_quantity, price=product_price))

            return True

    def update_order_quantity(self, order_id, new_quantity):
        """
        修改订单数量
        :param order_id: 要修改的order_id
        :param new_quantity: 新的数量
        """
        order = self.search_order(order_id)
        if not order:
            print('订单不存在')
            return False

        if order in self.orders:
            self.orders[self.orders.index(order)].quantity = new_quantity
            print('订单数量修改成功')
            return True
        else:
            print('订单不存在')
            return False

    def gen_order_id(self) -> str:
        try:
            order_id = max([int(order.order_id) for order in self.orders]) + 1
        except ValueError:
            order_id = 1
        return str(order_id)

    def get_order(self, order_id):
        order = self.search_order(order_id)
        if order:
            print(f'查询到订单{order}')
        else:
            print(f'您查询的订单{order_id}不存在')

    def search_order(self, order_id):
        for order in self.orders:
            if order.order_id == order_id:
                return order
        return None

    # @auth
    # 装饰器用不了
    def get_orders(self):
        if self.user_controller.current_user == 'admin':
            for order in self.orders:
                print(order)
        else:
            print('权限不足')
